package com.readpost.interceptors;

import com.readpost.doman.Result;
import com.readpost.utils.JWTUtil;
import com.readpost.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Log4j2
public class LoginInterceptor  implements HandlerInterceptor {

    /**
     * 拦截器，判断用户是否登录
     * @param request 请求对象
     * @param response 响应对象
     * @return true:放行，false:不放行
     */
    public boolean preHandle( final HttpServletRequest request, final @NotNull HttpServletResponse response, final @NotNull Object handler) {
        String token = request.getHeader("Authorization");
//        String Path = request.getRequestURI();
//        log.info("请求路径：{}", Path);
//        if(Path.equals("/ccc/user/login")||Path.equals("/ccc/user/register")){
//            return true;
//        }
        if (token == null) {
            response.setStatus(401);
            Result<String> result = Result.error(401, "未登录");
            System.out.println(result);
            return false;
        }
        try {
            Map<String, Object> claims = JWTUtil.verifyJWT(token);
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            Result<String> result = Result.error(401, e.getMessage());
            System.out.println(result);
            return false;
        }

    }

    /**
     * 拦截器，清除ThreadLocal中的数据
     * 此方法在请求处理完成后调用，无论请求是否成功
     */
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
       try{
            ThreadLocalUtil.remove();
       }
       catch (Exception e){
           log.error("清除ThreadLocal中的数据失败",e);
       }
    }
}
